//
//  ViewController.m
//  QQChatDemo
//
//  Created by zkingsoft on 16/1/9.
//  Copyright (c) 2016年 zkingsoft. All rights reserved.
//

#import "ViewController.h"
#import "MessageModel.h"

#import "LeftMessageTableViewCell.h"
#import "RightMessageTableViewCell.h"

#import "UITableView+SDAutoTableViewCellHeight.h"
#import "UIView+SDAutoLayout.h"

#import "UIImage+ResizeImage.h"

#import "ToolBarView.h"

@interface ViewController ()<UITableViewDataSource ,UITableViewDelegate, UITextFieldDelegate>{
    UITableView         *_tableView;
    
    // 数据源
    NSMutableArray      *_cellArray;
}

@property (nonatomic, strong) NSMutableArray        *modelArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    self.title = @"QQCHAT";
    [self loadData];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, K_WIDTH, K_HEIGHT-44) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:_tableView];
    
    if (!self.modelArray) {
        self.modelArray = [NSMutableArray new];
    }
    
    for (int i = 0; i < _cellArray.count; i++) {
        MessageModel *model = [[MessageModel alloc] init];
        
        model.timeString = [[_cellArray objectAtIndex:i] objectForKey:@"time"];
        
        model.textString = [[_cellArray objectAtIndex:i] objectForKey:@"text"];
        
        model.modelType = [[[_cellArray objectAtIndex:i] objectForKey:@"type"] intValue];
        
        [self.modelArray addObject:model];
    }
    
    [_tableView reloadData];
    //4.自动滚到最后一行
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_modelArray.count - 1 inSection:0];
    [_tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    // 添加工具栏
    ToolBarView *toolView = [[ToolBarView alloc] initWithFrame:CGRectMake(0, _tableView.frame.size.height+_tableView.frame.origin.y, K_WIDTH, 44)];
    toolView.inputTextField.delegate = self;
    toolView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:toolView];
    
    // 添加当键盘上去的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - UITextField的代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //1.获得时间
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"HH:mm"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    //2.创建一个MessageModel类
    MessageModel *message = [[MessageModel alloc] init];
    message.textString = textField.text;
    message.timeString = locationString;
    message.modelType = 0;
    
    
    //3.添加进去，并且刷新数据
    [self.modelArray addObject:message];
    
    [_tableView reloadData];
    NSLog(@"======%@", self.modelArray);
    
    //4.自动滚到最后一行
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:_modelArray.count - 1 inSection:0];
    [_tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
    textField.text = @"";
    
    return YES;
}

/**
 *  键盘frame发生改变的时候调用
 *
 *  @param note nil
 */
- (void)keyBoardWillChangeFrame:(NSNotification *)note{
    NSLog(@"%@", note.userInfo);
    NSDictionary *userInfo = note.userInfo;
    CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    
    CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    CGFloat moveY = keyFrame.origin.y - self.view.frame.size.height;
    
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, moveY);
    }];
}


/**
 *  加载数据
 */
- (void)loadData{
    _cellArray = [NSMutableArray array];
    
    // 加载plist中的数据 项目中从网络中请求过来数据进行展示的
    NSURL *dataUrl = [[NSBundle mainBundle] URLForResource:@"messages.plist" withExtension:nil];
    NSArray *dataArray = [NSArray arrayWithContentsOfURL:dataUrl];
    
    
    [_cellArray setArray:dataArray];
    [_tableView reloadData];
    
    NSLog(@"==的===%@", dataArray);
}

#pragma mark - tabbleViewdelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    // 这里需要注册一下模型cell  这个方法 是 当转换屏幕的时候 还是可以做到自适应的
    
    [_tableView startAutoCellHeightWithCellClass:[LeftMessageTableViewCell class] contentViewWidth:K_WIDTH];
    
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MessageModel  *modelType =  [_modelArray objectAtIndex:indexPath.row];
    int type = modelType.modelType;
    
    if (type == 1) {
        static NSString *leftIndefier = @"leftCell";
        LeftMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftIndefier];
        
        if (!cell) {
            cell = [[LeftMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftIndefier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.model = [self.modelArray objectAtIndex:indexPath.row];

        return cell;
    }else{
        static NSString *leftIndefier = @"rightCell";
        RightMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:leftIndefier];
        
        if (!cell) {
            cell = [[RightMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:leftIndefier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.model = [self.modelArray objectAtIndex:indexPath.row];
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 根据模拟 获取cell的高度并返回
    
    
    // indextPath 为cell路径
    // model 为数据
    // keyPath  model属性名
    return [_tableView cellHeightForIndexPath:indexPath model:self.modelArray[indexPath.row] keyPath:@"model"];
}


// 当开始拖动tableview的时候调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}



// 移除代理
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
